import 'dart:io';

import 'package:path_provider/path_provider.dart';

class CacheUtils {
  /// 加载缓存
  Future<String> loadCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(tempDir);
    // print('临时目录大小: ' + value.toString());
    return _renderSize(value);
  }

  /// 传入根目录，用递归的方法计算出文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List children = file.listSync();
      double total = 0;
      if (children != null)
        for (final FileSystemEntity child in children)
          total += await _getTotalSizeOfFilesInDir(child);
      return total;
    }
    return 0;
  }

  /// 清除缓存
  Future<String> clearCache() async {
    //此处展示加载loading
    await Future.delayed(Duration(seconds: 1), () async {});
    FileSystemEntity file = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(file);
    print("$value");
    if (value <= 0) {
      // ToastUtils.show('暂无缓存');
      return "0.0k";
    } else if (value >= 0) {
      // var hide = ToastUtil.showLoadingText_iOS(context, msg: "正在清理中...");

      //删除缓存目录
      try {
        await delDir(file);
      } catch (e) {
        return null;
      }
      // await loadCache();
      // ToastUtils.show('清理完成');
      return await loadCache();
    }
  }

  /// 递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
    await file.delete();
  }

  /// 格式化缓存大小
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }
}
